package com.learning.servlet2x.filter.gzip;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;

/**
 * ClassName: GZipServlet
 * Description: 使用 GZIP 压缩
 * Date:  2014-10-12 21:16 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
public class GzipServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //实现压缩
        String tDate = "准备被压缩的数据";
        System.out.println("压缩前的数据大小：  " + tDate.getBytes().length);

        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        GZIPOutputStream gout = new GZIPOutputStream(bout);
        gout.write(tDate.getBytes());
        gout.flush();
        gout.finish();
        gout.close();//写到字节数组流中
        // 得到压缩后的数据
        byte[] gzip = bout.toByteArray();
        System.out.println("压缩后的数据大小：  " + gzip.length);

        // 通知浏览器数据采用压缩格式
        // 压缩格式
        resp.setHeader("Content-Encoding", "gzip");
        // 压缩数据的长度
        resp.setHeader("Content-Length", gzip.length + "");
        resp.getOutputStream().write(gzip);
    }
}
